﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Criterion;
using SinBiota.Model.Entities;
using SinBiota.Model.Persistence.Repositories.Interfaces;
using NHibernate;

namespace SinBiota.Model.Persistence.Repositories.Implementation
{
    public class UserRepository : RepositoryAbstract<User,int>, IUserRepository
    {
        private readonly IProjectRepository _projectRepository;
        public UserRepository(ISession session, IProjectRepository projectRepository) : base(session)
        {
            _projectRepository = projectRepository;
        }

        public User FindByUsername(string username)
        {
            return FindByEqRestrictionUniqueResult(x=>x.Username, username);
        }

        public IList<User> FindByEmail(string email)
        {
            return FindByEqRestrictionListResult(x=>x.Email, email);
        }

        public User FindByName(string name)
        {
            return FindByEqRestrictionUniqueResult(x => x.Name, name);
        }

        public IList<User> FindByNameOrUsernameLike(string search)
        {
            var inffix = "%" + search + "%";
            return Session.CreateCriteria<User>().Add(
                Restrictions.Like("Name", inffix) ||
                Restrictions.Like("Username", inffix)
                ).List<User>();
        }

        public void Update(User editUser, string[] coordinatorProjectTitles, string[] memberProjectTitles)
        {
            // Remove original projects:
            while (editUser.MemberProjects.Count>0)
                editUser.MemberProjects.RemoveAt(0);
            while (editUser.CoordinatorProjects.Count>0)
                editUser.CoordinatorProjects.RemoveAt(0);
            // Add:
            if (memberProjectTitles != null)
            {
                var memberProjects = memberProjectTitles.Select(title => _projectRepository.FindByName(title)).ToList();
                foreach (var project in memberProjects)
                {
                    editUser.MemberProjects.Add(project);
                }
            }
            if (coordinatorProjectTitles != null)
            {
                var coordinatorProjects = coordinatorProjectTitles.Select(title => _projectRepository.FindByName(title)).ToList();
                foreach (var project in coordinatorProjects)
                {
                    editUser.CoordinatorProjects.Add(project);
                }
            }
            // Now update all:
            SaveOrUpdate(editUser);
        }
    }
}
